package com.shensi.adminCollect.controller.station;

import com.shensi.common.core.controller.BaseController;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.page.TableDataInfo;
import com.shensi.common.redis.service.RedisCache;
import com.shensi.adminCollect.service.customer.ActivityMessagePushRecordService;
import com.shensi.adminCollect.domain.station.CouponActivity;
import com.shensi.adminCollect.domain.station.DrawCoupon;
import com.shensi.adminCollect.service.station.CouponActivityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.common.core.domain.entity.SysUser;
/**
 * @Auther: LogicQin
 * @Date: 2023/8/4 12:10
 * @Description:
 */
@RestController
@RequestMapping("/coupon/activity")
@Api(tags = "优惠券活动管理")
public class CouponActivityController extends BaseController {

    @Autowired
    private CouponActivityService couponActivityService;
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ActivityMessagePushRecordService activityMessagePushRecordService;

    @PostMapping("/add")
    @ApiOperation("新增优惠券活动")
    @Transactional
    public AjaxResult addCouponActivity(@RequestBody CouponActivity couponActivity) {

        AjaxResult a = couponActivityService.checkCouponActivity(couponActivity);
        if (a.get("code") != null && a.get("code") instanceof Integer && (Integer) a.get("code") == 200) {

        } else {
            String errorMsg = a.get("msg").toString();
            return AjaxResult.error(errorMsg);
        }
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        // 先新增优惠券活动
        if (user.getUserLevel() == null) {
            couponActivity.setCreateBy("admin");
            return AjaxResult.error("admin不能新增优惠券");
        } else if (user.getUserLevel() != null && user.getUserLevel().equals("1")) {
            couponActivity.setCreateBy(user.getUserName());
            couponActivity.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel().equals("2")) {
            couponActivity.setCreateBy(user.getUserName());
        }
        if(couponActivity.getMemberCondition().equals("all")){
            String str = "[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"]";
            String strMemberLevel = "[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\"]";
            couponActivity.setMemberLevelList(strMemberLevel);
            couponActivity.setPayMentList(str);
        }
        couponActivityService.addCouponActivity(couponActivity);

        long currentTime = System.currentTimeMillis();
        long expireMillis = 0;
        int expireSeconds = 0;
        if (couponActivity.getActivityEndTime() != null) {
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date endTime = dateFormat.parse(couponActivity.getActivityEndTime());
                expireMillis = endTime.getTime() - currentTime;
                expireSeconds = (int) (expireMillis / 1000);
                redisCache.setCacheObject("activity:" + couponActivity.getId(), "优惠券信息", expireSeconds, TimeUnit.SECONDS);


            } catch (ParseException e) {
                e.printStackTrace();
            }

        }

        return AjaxResult.success("新增成功");
    }

    /**
     * 分类
     */
    @PostMapping("/amtForList")
    @ApiOperation(value = "查询优惠劵列表", httpMethod = "POST")
    public AjaxResult amtForList(@RequestBody  List<String> issueIds) {
        return  couponActivityService.amtForList(issueIds);
    }





    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除优惠券活动")
    @Transactional
    public AjaxResult deleteCouponActivity(@PathVariable String id) {
        // 删除与优惠券活动关联的发放关系
        CouponActivity couponActivity = couponActivityService.getCouponActivityById(id);
        if (couponActivity != null && couponActivity.getActivityStatus().equals("1")) {
            // 状态为1，禁止删除
            return AjaxResult.error("该优惠券活动正在生效中，禁止删除");
        }
        couponActivityService.deleteCouponActivityRelaById(id);
        couponActivityService.deleteCouponActivityById(id);
        return AjaxResult.success("删除成功");
    }

    @PostMapping("/batch/delete")
    @Transactional
    public AjaxResult batchDeleteCouponActivities(@RequestBody List<String> idList) {
        for (String id : idList) {
            // 删除与优惠券活动关联的发放关系
            CouponActivity couponActivity = couponActivityService.getCouponActivityById(id);
            if (couponActivity != null && couponActivity.getActivityStatus().equals("1")) {
                // 状态为1，禁止删除
                return AjaxResult.error("该优惠券活动正在生效中，禁止删除");
            }
        }
        for (String id : idList) {
            // 删除与优惠券活动关联的发放关系
            couponActivityService.deleteCouponActivityRelaById(id);
        }
        int deletedCount = couponActivityService.batchDeleteCouponActivities(idList);
        if (deletedCount > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    @ApiOperation(value = "手动发券", httpMethod = "POST")
    @PostMapping("/drawCoupons")
    public AjaxResult drawCoupons(@RequestBody DrawCoupon drawCoupon) {
        drawCoupon.setActivityType(4);
        AjaxResult a = couponActivityService.sendCoupon(drawCoupon);

        return a;
    }

    @ApiOperation(value = "手动发券", httpMethod = "POST")
    @PostMapping("/drawCouponsSingle")
    public AjaxResult drawCouponsSingle(@RequestBody List<String> couponIssueIdList, @RequestParam String mobilePhone,@RequestParam Long enterpriseId) {
        DrawCoupon drawCoupon = new DrawCoupon();
        drawCoupon.setCouponIssueIdList(couponIssueIdList);
        drawCoupon.setActivityType(4);
        drawCoupon.setMobilePhoneList(Collections.singletonList(mobilePhone));
        drawCoupon.setEnterpriseId(enterpriseId); // 添加企业ID
        AjaxResult result = couponActivityService.sendCoupon(drawCoupon);
        return result;
    }

    public AjaxResult drawCouponsSuper(@RequestBody List<String> couponIssueIdList, @RequestParam String mobilePhone,@RequestParam Long enterpriseId) {
        DrawCoupon drawCoupon = new DrawCoupon();
        drawCoupon.setCouponIssueIdList(couponIssueIdList);
        drawCoupon.setActivityType(7);
        drawCoupon.setMobilePhoneList(Collections.singletonList(mobilePhone));
        drawCoupon.setEnterpriseId(enterpriseId); // 添加企业ID
        AjaxResult result = couponActivityService.sendCoupon(drawCoupon);
        return result;
    }



    @PutMapping("/update")
    @ApiOperation("修改优惠券活动")
    @Transactional
    public AjaxResult updateCouponActivity(@RequestBody CouponActivity couponActivity) {
        AjaxResult a = couponActivityService.checkCouponActivity(couponActivity);
        if (a.get("code") != null && a.get("code") instanceof Integer && (Integer) a.get("code") == 200) {

        } else {
            String errorMsg = a.get("msg").toString();
            return AjaxResult.error(errorMsg);
        }
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        // 先新增优惠券活动
        if (user.getUserLevel() == null) {
            couponActivity.setUpdateBy("admin");
        } else if (user.getUserLevel() != null && user.getUserLevel().equals("1")) {
            couponActivity.setUpdateBy(user.getUserName());
        } else if (user.getUserLevel().equals("2")) {
            couponActivity.setUpdateBy(user.getUserName());
        }
        if(couponActivity.getMemberCondition().equals("all")){
            String str = "[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"]";
            String strMemberLevel = "[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\"]";
            couponActivity.setMemberLevelList(strMemberLevel);
            couponActivity.setPayMentList(str);
        }
        couponActivityService.updateCouponActivity(couponActivity);
        // 删除旧的Redis缓存
        redisCache.deleteObject("activity:" + couponActivity.getId());

        // 添加新的Redis缓存
        long currentTimeMillis = System.currentTimeMillis();
        long expireMillis = 0;
        int expireSeconds = 0;
        if (couponActivity.getActivityEndTime() != null) {
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date endTime = dateFormat.parse(couponActivity.getActivityEndTime());
                expireMillis = endTime.getTime() - currentTimeMillis;
                expireSeconds = (int) (expireMillis / 1000);
                redisCache.setCacheObject("activity:" + couponActivity.getId(), "优惠券信息", expireSeconds, TimeUnit.SECONDS);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.success("修改成功");
    }

    @GetMapping("/get/{id}")
    @ApiOperation("根据ID查询优惠券活动")
    public CouponActivity getCouponActivity(@PathVariable String id) {
        return couponActivityService.getCouponActivityById(id);
    }

    @GetMapping("/getAll")
    @ApiOperation("查询所有优惠券活动")
    public TableDataInfo getAllCouponActivities(CouponActivity couponActivity) {
        startPage();
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        // 先新增优惠券活动
        if (user.getUserLevel() == null) {
            couponActivity.setCreateBy("admin");

        } else if (user.getUserLevel() != null && user.getUserLevel().equals("1")) {
            couponActivity.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel().equals("2")) {
        }
        return getDataTable(couponActivityService.getAllCouponActivities(couponActivity));

    }

    @GetMapping("/getAllLabel")
    @ApiOperation("查询包含标签的优惠券活动")
    public TableDataInfo getAllLabel(CouponActivity couponActivity) {
        startPage();
        couponActivity.setUserMentList("1");
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        // 先新增优惠券活动
        if (user.getUserLevel() == null) {
            couponActivity.setCreateBy("admin");

        } else if (user.getUserLevel() != null && user.getUserLevel().equals("1")) {
            couponActivity.setEnterpriseId(user.getEnterpriseId());
        } else if (user.getUserLevel().equals("2")) {
        }
        return getDataTable(couponActivityService.getAllCouponActivities(couponActivity));

    }

    @PutMapping("/updateStatus/{activityId}/{activityStatus}")
    @ApiOperation("更新优惠券活动状态")
    public void updateActivityStatus(@PathVariable String activityId, @PathVariable String activityStatus) {
        couponActivityService.updateActivityStatus(activityId, activityStatus);
    }
}
